package com.gupt.reggie.service.impl;/*
@author name
@data 2023/4/17-18:17
*/


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gupt.reggie.common.CustomException;
import com.gupt.reggie.entity.Employee;
import com.gupt.reggie.mapper.EmployeeMapper;
import com.gupt.reggie.service.EmployeeService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Service                            //mybatis-plus 提供的结构规范
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {
    @Override
    public Employee login(HttpServletRequest request, Employee employee) {

        //客户端发送的代码用md5加密处理
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //根据页面提交的username查询数据库信息
        //创建一个条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件       queryWrapper.eq(”a“，”b“） ==  a==b
        queryWrapper.eq(Employee::getUsername, employee.getUsername());
        //执行查询语句
        Employee emp = this.getOne(queryWrapper);  //查询数据库为唯一的对象，则调用getOne()

        //校验:查不到对应信息
        if (emp == null) {
            throw new CustomException("登录失败,该用户不存在");
        }

        //校验：密码是否一致
        if (!emp.getPassword().equals(password)) {
            throw new CustomException("密码错误");
        }

        //校验：查看员工状态
        if (emp.getStatus() == 0) {   //0为禁用
            throw new CustomException("该账号已禁用");
        }

        //登录校验成功
        request.getSession().setAttribute("employee", emp.getId());

        return emp;
    }

    @Override
    public Page page(int page, int pageSize, String name) {
        log.info("page = {},pageSize = {},name = {}",page,pageSize,name);

        //构造分页构造器
        Page pageInfo = new Page(page,pageSize);  //第几页，一页多少数据

        //构造条件构造器
        LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper();

        //添加过滤（查询 条件  eq：相等  like：模糊
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);

        //添加排序条件
        lambdaQueryWrapper.orderByDesc(Employee::getCreateTime);

        //执行查询
        pageInfo = this.page(pageInfo,lambdaQueryWrapper);

        return pageInfo;
    }
}
